<template>

  <a-tooltip @click="toMyAnnouncement" style="cursor:pointer">
    <template slot="title">
      {{$t('m.system.portal.entity.message')}}
    </template>
    <a-badge :count="msgTotal">
      <a-icon type="sound" :style="{ fontSize: '18px', padding: '0 10px'}"/>
    </a-badge>
  </a-tooltip>

</template>

<script>

import {getAction} from '@/api/manage'
import store from '@/store/'
import YchConstant from "@/api/YchConstant";

export default {
  name: "UserMessage",
  data() {
    return {
      url: {
        listCementByUser: YchConstant.PREFIX_SYSTEM + "/annountCement/listByUser",
      },
      msg1Count: "0",
      msg2Count: "0",
      stopTimer: false,
      websock: null,
      lockReconnect: false,
    }
  },
  computed: {
    msgTotal() {
      return parseInt(this.msg1Count) + parseInt(this.msg2Count);
    }
  },
  mounted() {
    this.loadData();
    this.initWebSocket();
  },
  methods: {
    loadData() {
      try {
        // 获取系统消息
        getAction(this.url.listCementByUser).then((res) => {
          if (res.success) {
            this.msg1Count = res.result.anntMsgTotal;
            this.msg2Count = res.result.sysMsgTotal;
          }
        }).catch(() => {
          this.stopTimer = true;
        });
      } catch (err) {
        this.stopTimer = true;
      }
    },
    toMyAnnouncement() {
      this.$emit("toMyAnnouncement")
    },
    initWebSocket: function () {
      let userId = store.getters.userInfo.id;
      // 统一从nginx或vue.config.js中转发，减少后台开放接口
      // let baseUrl = location.protocol + "//" + location.host
      // let url = baseUrl.replace("https://", "wss://").replace("http://", "ws://") + "/websocket/" + userId;
      let url = bootConfig[process.env.NODE_ENV].VUE_APP_URL.replace("https://", "wss://").replace("http://", "ws://") + "/websocket/" + userId;
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
    },
    websocketOnopen: function () {
      //console.log("WebSocket连接成功");
    },
    websocketOnerror: function (e) {
      //console.log("WebSocket连接发生错误");
      this.reconnect();
    },
    websocketOnmessage: function (e) {
      if (e.data && e.data === 'ok') {
        return
      }
      let data = eval("(" + e.data + ")"); //解析对象
      if (data.cmd === "topic") {
        //系统通知
        this.loadData();
      } else if (data.cmd === "user") {
        //用户消息
        this.loadData();
      }
    },
    websocketOnclose: function (e) {
      this.reconnect();
    },
    reconnect() {
      var that = this;
      if (that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
  }
}
</script>
